import os
from flask import Blueprint, render_template, flash, redirect, url_for, make_response, request, current_app
from app.email import send_mail
from app.extensions import db, photos
from app.forms.user import RegisterForm, LoginForm, ChangepawdForm, ChangeiconForm, ChangeemailForm, FindpawdForm,FindpawdFormTwo
from app.models import User, Posts, RePosts,PingTexts,HuiTexts
from flask_login import login_user,current_user,login_required,logout_user
from PIL import Image

user = Blueprint('user', __name__)

@user.route('/register',methods=['GET','POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        #创建User模型
        user = User(username=form.username.data,password=form.password.data,email=form.email.data)
        #保存到数据库
        db.session.add(user)
        # 此时用户还没有添加到数据库中
        # 需要手动提交一次
        db.session.commit()
        #发送账户激活邮件
        token = user.gennerate_activte_token()
        send_mail(form.email.data,'账号激活','email/activte',token=token,username=user.username)
        flash('注册成功，激活邮件已发送至注册邮箱，请前往激活！')
        return redirect(url_for('main.index'))
    return render_template('user/register.html',form=form)
# 账户激活
@user.route('/activte/<token>')
def activte(token):
    if User.check_activte_token(token):
        flash('账户激活成功')
        return redirect(url_for('user.login'))
    else:
        flash('激活失败')
        return redirect(url_for('main.index'))

@user.route('/login',methods=['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # 取出username并再数据库中判断
        if User.query.filter_by(username=form.username.data).first():
            #出去了username
            u = User.query.filter_by(username=form.username.data).first()
            if u.verify_password(form.password.data):
                #判断正确，可以登录
                login_user(u,remember=form.remember.data)
                # 判断有没有下一页，没有则跳转到主页
                return redirect(request.args.get('next') or url_for('main.index'))
            else:
                flash('无效的密码')
        else:
            flash('用户名不存在')
    return render_template('user/login.html',form=form)

@user.route('/logout')
# 保护路由
@login_required
def logout():
    # 退出当前登录的用户
    logout_user()
    flash('您已退出登录')
    return redirect(url_for('main.index'))

# 个人信息
@user.route('/profile')
@login_required
def profile():
    return render_template('user/profile.html')

# 修改密码
@user.route('/changepawd',methods=['GET','POST'])
@login_required
def changepawd():
    form = ChangepawdForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            current_user.password = form.verify_newpassword.data
            db.session.add(current_user)
            db.session.commit()
            flash('修改成功,请使用新密码登录！💊')
            return redirect('user/logout/')
        else:
            flash('原密码输入错误')
    return render_template('user/changepawd.html',form=form)

# 修改头像
@user.route('/changeicon',methods=['GET','POST'])
@login_required
def changeicon():
    form = ChangeiconForm()
    if form.validate_on_submit():
        # 生成随机文件名
        # 获取文件的后缀名
        suffix = os.path.splitext(form.icon.data.filename)[1]
        #生成一个随机的文件名来拼接这个后缀名
        name = rand_str()+suffix
        photos.save(form.icon.data,name=name)
        # 生成缩略图
        pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],name)
        img = Image.open(pathname)
        img.thumbnail((100,100))
        img.save(pathname)
        # 删除原来的
        if current_user.icon != '001.jpg':
            os.remove(os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],current_user.icon))
        # 保存到数据库中
        current_user.icon = name
        db.session.add(current_user)
        flash('头像已修改')
    return render_template('user/changeicon.html',form=form)
# 生成一个随机字符串
def rand_str(length=32):
    import random
    base_str = 'abcdefghijklmnopqrstuvwxyz1234567890'
    return ''.join(random.choice(base_str) for i in range(length))

# 修改邮箱
@user.route('/changeemail',methods=['GET','POST'])
@login_required
def changeemail():
    form = ChangeemailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            # 密码验证成功应该发送验证激活邮件
            email = form.changeeamil.data
            token = email+','+str(current_user.id)
            send_mail(email, '修改邮箱验证邮件', 'email/activteemail',token=token, username=current_user.username)
            flash('操作成功，请前往邮箱完成验证！')
        else:
            flash('密码输入错误')
    return render_template('user/changeemail.html',form=form)

# 邮箱修改激活
@user.route('/activteemail/<token>')
@login_required
def activteemail(token):
    mystr = token.split(',')
    myid = int(mystr[1])
    newemail =mystr[0]
    user = User.query.get(myid)
    user.email = newemail
    db.session.add(user)
    flash('修改成功，请以后使用修改后的邮箱')
    return redirect(url_for('main.index'))

# 找回密码
@user.route('/findpawd',methods=['GET','POST'])
def findpawd():
    form = FindpawdForm()
    if form.validate_on_submit():
        if User.query.filter_by(email=form.username.data).first() is None:
            flash('邮箱不存在，请重新输入！')
        else:
            email = form.username.data
            token = email
            send_mail(email, '找回密码验证邮件', 'email/findpawd', token=token)
            flash('邮件已发送，请在邮件中点击修改密码')
    return render_template('user/findpawd.html',form=form)

# 确认修改密码
@user.route('/activtepawd/<token>',methods=['GET','POST'])
def activtepawd(token):
    form = FindpawdFormTwo()
    user = User.query.filter_by(email=token).first()
    if form.validate_on_submit():
        user.password = form.new_password.data
        db.session.add(user)
        flash('修改成功，请使用修改后的密码登录')
        return redirect(url_for('user.login'))
    return render_template('user/findpawdtwo.html',form=form)

# 用户帖子详情
@user.route('/userposts')
@login_required
def userposts():
    # 获取用户的帖子
    page = request.args.get('page', 1, type=int)
    newpost = Posts.query.filter_by(uid=current_user.id).order_by(db.desc(Posts.timestamp)).paginate(page, 3, error_out=True)
    newposts = newpost.items
    return render_template('user/userposts.html',newlist=newposts,pagination=newpost)

# 帖子详情   有bug  应该必须知道我回复给谁 同时还要知道评论了他的那个帖子！！！！
@user.route('/postinfo/<int:pid>',methods=['GET','POST'])
def postinfo(pid):
    post = Posts.query.filter_by(id=pid).first()
    bid = post.user.username
    # rpost = RePosts.query.filter_by(bid=bid).all()
    ppost = PingTexts.query.filter_by(p_pid=pid).all()
    return render_template('posts/postinfo.html',post=post,ppost=ppost)

# 用户帖子详情
@user.route('/newuserposts/<int:uid>',methods=['GET','POST'])
def newuserposts(uid):
    # 获取指定用户的所有帖子
    page = request.args.get('page', 1, type=int)
    newpost = Posts.query.filter_by(uid=uid).order_by(db.desc(Posts.timestamp)).paginate(page, 3, error_out=True)
    newposts = newpost.items
    return render_template('user/userposts.html',newlist=newposts,pagination=newpost)